package fun.tan90.device.main.listener;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import fun.tan90.device.main.mapper.db1.PluginInfoMapper;
import fun.tan90.device.main.model.dataobject.db1.PluginInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.event.AppLoadEndEvent;
import org.noear.solon.core.event.EventListener;
import org.noear.solon.hotplug.PluginManager;

import java.io.File;
import java.util.List;

@Slf4j
@Component
public class AppLoadEndEventListener implements EventListener<AppLoadEndEvent> {

    @Db("db1")
    PluginInfoMapper pluginInfoMapper;

    @Override
    public void onEvent(AppLoadEndEvent event) throws Throwable {
        List<PluginInfo> pluginInfos = pluginInfoMapper.selectList(Wrappers.lambdaQuery(PluginInfo.class)
                .select(PluginInfo::getPluginName, PluginInfo::getPluginPath)
                .eq(PluginInfo::getEnable, "1")
        );
        pluginInfos.forEach(pluginInfo -> {
            String pluginPath = pluginInfo.getPluginPath();
            if (FileUtil.exist(pluginPath)) {
                PluginManager.add(pluginInfo.getPluginName(), new File(pluginPath));
                PluginManager.start(pluginInfo.getPluginName());
            } else {
                log.warn("【{}】插件不存在：【{}】", pluginInfo.getPluginName(), pluginPath);
            }
        });
    }
}